<?php
/**
 * Created by PhpStorm.
 * User: Guangpeng Chen
 * Date: 15-1-8
 * Time: 上午10:47
 */
use \PFT\Db;
use \LaneWeChat\Core\Permission;
include '/var/www/html/wx/wechat/open_wechat.php';
include '/var/www/html/new/d/common/func.inc.php';
include_once '/var/www/html/new/d/module/common/Db.class.php';
$dbConf = include '/var/www/html/new/d/module/common/db.conf.php';// 远端服务器配置信息
Db::Conf($dbConf['remote_1']);

$info = Permission::getInfo($_SESSION['sid']);
define('WECHAT_APPID', $info[$_REQUEST['hash']]['appid']);

$action = $_REQUEST['action'];

//echo WECHAT_APPID;
switch ($action) {
    case 'SendMsg':
        $msg_type = trim($_POST['msg_type']);
        if ($msg_type=='text') {
            $fansList = \LaneWeChat\Core\UserManage::getFansList();
            $content  = $_POST['content'];
            $result   = \LaneWeChat\Core\AdvancedBroadcast::sentTextByOpenId($fansList['data']['openid'], $content);
        }
        elseif ($msg_type=='news') {
            $show_pic = 0;
            $list = array();
            $content    = $_POST['content'];
            $title      = safetxt($_POST['title']);
            if (!$title) {
                \LaneWeChat\Response('标题不能为空','fail','script');
            }
            if (!$content) {
                \LaneWeChat\Response('内容不能为空','fail','script');
            }
            if ($_FILES['image']['size']>0) {
                include '/var/www/html/new/d/class/Uploader.class.php';
                $path = getcwd();
                $config = array(
                    'simpleFolder'=>true,
                    "savePath" => '/var/www/html/wx/wechat/images',
                    "maxSize" => 1024, //单位KB
                    "allowFiles" => array(".gif", ".png", ".jpg", ".jpeg", ".bmp"),
                );
                $up = new Uploader("image", $config);
                $info = $up->getFileInfo();
                //上传图片到公众平台
                $menuId = \LaneWeChat\Core\Media::upload($info['url'], 'image');
                if (empty($menuId['media_id'])) {
                    \LaneWeChat\Response('图片上传失败','fail','script');
                }
                $show_pic = 1;
            } else {
                \LaneWeChat\Response('封面不能为空','fail','script');
            }
            $author     = safetxt($_POST['author']);

            $url        = safetxt($_POST['source_url']);
            $digest     = safetxt($_POST['digest']);

            //TODO::微信群发消息
            $list[] = array(
                'thumb_media_id'=>$menuId['media_id'] ,
                'author'=> $author,
                'content'=>$content,
                'title'=> $title,
                'content_source_url'=>$url,
                'digest'=>$digest,
                'show_cover_pic'=>$show_pic,
            );
//            print_r($list);
            $mediaId = \LaneWeChat\Core\AdvancedBroadcast::uploadNews($list);
//        var_dump($mediaId);
            //给粉丝列表的用户群发图文消息
            if (!isset($_POST['fans_group']) || $_POST['fans_group']==-1 ) {
                $fansList = \LaneWeChat\Core\UserManage::getFansList();
                print_r($fansList);
                $result = \LaneWeChat\Core\AdvancedBroadcast::sentNewsByOpenId($fansList['data']['openid'], $mediaId);
            } else {
                $result = \LaneWeChat\Core\AdvancedBroadcast::sentNewsByGroup(intval($_POST['fans_group']), $mediaId);
            }
        }
        if ($result['errcode']==0) {
            $msg = '发送成功' . $result['errmsg'];
        } else {
            $msg = '发送失败，错误信息:'. $result['errmsg'];
        }
        \LaneWeChat\Response($msg, 'ok', 'script');
        break;
    case 'GetWxGrpList':
        //获取分组
        $grps = \LaneWeChat\Core\UserManage::getGroupList();
        echo json_encode($grps['groups']);
        break;
    case 'GetWechatBinded':
        $accounts = array();
        foreach ($info as $acc) {
            $accounts[] = array(
                'id'=>$acc['id'],
                'name'=>$acc['nick_name'],
            );
        }
//        $accounts = \LaneWeChat\Core\Ext::AccountList($_SESSION['sid']);
        if (count($accounts)) {
            echo json_encode(array('status'=>'ok', 'list'=>$accounts));
        } else {
            echo json_encode(array('status'=>'fail', 'msg'=>'您还没有绑定过微信账号'));
        }
        break;
    case 'GetWechatHash':
        $sqlHash = "SELECT hash,ac_type FROM pft_wx WHERE fid=? LIMIT 1";
        $stmt = \LaneWeChat\Core\Db::Connect()->prepare($sqlHash);
        $stmt->execute(array($_SESSION['sid']));
        $ret = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($ret) {
            $ret = '{"status":"ok","key":{"hash":"'.$ret['hash'].'","ac_type":"'.$ret['ac_type'].'"}}';
        }else {
            $ret = '{"status":"fail","msg":"您尚未绑定微信公众号，请先绑定公众号后再添加菜单"}';
        }
        echo $ret;
        break;
    //获取已有功能的菜单项
    case 'GetExistAction':
        if ($_SESSION['memberID']==51431) {
            //新版微信菜单栏配置地址
            $actions = include '/var/www/html/wx/wechat/16u_action.config.php';
        } else {
            $actions = include '/var/www/html/wx/wechat/dev_action.config.php';
        }
        if ($info) {
//            $actions = include '/var/www/html/wx/wechat/dev_action.config.php';
//            if ($info[$_GET['hash']]['service_type_info']==2) {//服务号
//                $actions = include '/var/www/html/wx/wechat/dev_action.config.php';
//            } else {//订阅号
//                $actions = include '/var/www/html/wx/wechat/subaction.config.php';
//            }
            $ret = json_encode(array('status'=>'ok', 'list'=>$actions));
            $search  = array('%DOMAIN%','%HASH%','%WECHAT_APPID%', '%FID%');
            $replace = array($_SESSION['saccount'],$hash, WECHAT_APPID, $_SESSION['sid']);
            $ret = str_replace($search, $replace, $ret);
        } else {
            $ret = '{"status":"fail","msg":"您尚未绑定微信公众号，请先绑定公众号后再添加菜单"}';
        }
        echo $ret;
        break;
    //创建菜单
    case 'CreateMenu':
//        print_r($_POST['data']);exit;
//        print_r($info);exit;
        if ( $info[$_REQUEST['hash']]['verify_type_info']==-1 && $info[$_REQUEST['hash']]['service_type_info']==1) {
            \LaneWeChat\Response('抱歉，未认证的订阅号无法创建菜单', 'fail');
        }
        $menuList = $_POST['data'];
        //存储数据
//        echo WECHAT_APPID;
        //将客户端传过来值为“-1”的数据转成空
        foreach ($menuList as $key=>$menu) {
            foreach($menu as $k=>$m) {
                if ($m==-1) $menuList[$key][$k] = '';
            }
        }
//        print_r($menuList);
//        echo WECHAT_APPID;exit;
        $res = \LaneWeChat\Core\Menu::setMenu($menuList, WECHAT_APPID);
        if ($res === true) {
            $menuFile = '/var/www/html/wx/wechat/menu/menu_' . WECHAT_APPID;
            \LaneWeChat\Core\Ext::CacheFile( json_encode($_POST['data']), $menuFile);
//            wxa544a548c904b9b3
            \LaneWeChat\Response('', 'ok');
        }
        \LaneWeChat\Response($res['errmsg']);
        break;
    case 'GetMenu':

//        echo WECHAT_APPID;
//        print_r($info);
//        echo $info[$_GET['hash']]['appid'];
        $menuFile = '/var/www/html/wx/wechat/menu/menu_' . $info[$_GET['hash']]['appid'];
        if (file_exists($menuFile)) {
            $menu = file_get_contents($menuFile);
            if (!empty($menu)) {
                echo $menu;
            } else {
                echo '[]';
            }
        } else {
            echo '[]';
        }
        break;
    case 'TestMenu':
        print_r( \LaneWeChat\Core\Menu::getMenu());
        break;
    case 'UploadImage':
        if ($_FILES['image']['size']>0) {
            include '/var/www/html/new/d/class/Uploader.class.php';
            $callback = $_POST["callback"];
            $path = getcwd();
            $config = array(
                'simpleFolder'=>true,
                "savePath" => '/var/www/html/wx/wechat/images',
                "maxSize"  => 1024, //单位KB
                "allowFiles" => array(".gif", ".png", ".jpg", ".jpeg", ".bmp"),
            );
            $up = new Uploader("image", $config);
            $info = $up->getFileInfo();
            if ($info['state']=='SUCCESS') {
                $json = '{"status":"ok", "key":"http://wx.12301.cc/wechat/images/' . $info['name'].'"}';
            } else {
                $json = '{"status":"fail"}';
            }
            echo '<script>window.parent.'.$callback.'('.$json.');</script>';
        }
        break;
    case 'SetKeyWord':
        $hash = $_POST['hash'];//选中的公众号
        $key  = safetxt($_POST['keyword']);
        //特殊配置
        if (isset($_POST['msg_type']) && strtoupper($_POST['msg_type'])=='IMAGE') {
            if (isset($_POST['lists'])) {
                foreach ($_POST['lists'] as $list) {
//                    echo $list['title'];
                    //图文回复：IMAGE|标题|图片|摘要|地址
                    $title  = safetxt($list['title']);//标题不能超过30字
                    $digest = safetxt($list['digest']);//摘要不能超过100字
                    $img    = safetxt($list['img']);
                    if (!$title) {
                        \LaneWeChat\Response('标题不能为空','fail');
                    }
                    if (mb_strlen($title, 'utf-8')>90) {
                        \LaneWeChat\Response('标题不能超过30字','fail');
                    }
                    if (!empty($digest) && mb_strlen($digest, 'utf-8')>300) {
                        \LaneWeChat\Response('摘要不能超过100字','fail');
                    }
                    $url    = safetxt($list['source_url']);
//                    $short_url_json = file_get_contents("http://api.t.sina.com.cn/short_url/shorten.json?source=1961808079&url_long={$url}");
//                    $arr    = json_decode($short_url_json);
//                    $url = $arr[0]->url_short;
                    $word[] = array(
                        'title'     =>$title,
                        'digest'    => $digest,
                        'img'       => $img,
                        'source_url' => $url,
                    );//"IMAGE|{$title}|$img|$digest|$url";
                }
                $word = serialize($word);
                $msg_type = 2;
            }
        }
        else {
            $msg_type = 1;
            $word = safetxt($_POST['response']);
        }
        $res = \LaneWeChat\Core\OpenExt::SetKeyWord(WECHAT_APPID, $key, $word, $msg_type);
        \LaneWeChat\Response($res['msg'], $res['status']);
        break;
    case 'GetKeyWord':
        $list = \LaneWeChat\Core\OpenExt::GetKeyWordList(WECHAT_APPID );
        if ($list) {
            echo json_encode(array('status'=>'ok', 'lists'=>$list));
        } else {
            echo '{"status":"ok","list":[]}';
        }
        break;
    case 'GetSpecialResp':
        $hash = intval($_GET['hash']);
        $key  = safetxt($_GET['key']);
        $resp = \LaneWeChat\Core\OpenExt::GetKeyWord(WECHAT_APPID, $key);
//        print_r($resp);
        $output = array('status'=>'ok');
        if ($resp['msg_type']==2) {
            $output['lists'] = unserialize($resp['response']);
            $output['msg_type']  = 'IMAGE';//$resp['msg_type']==2?  : 'TEXT';
        }
        elseif ($resp['msg_type']==1) {
            $output['lists'] = $resp['response'];
            $output['msg_type']  = 'TEXT';//$resp['msg_type']==2?  : '';
        }
        echo json_encode($output);
        break;
    case 'RemoveKewWord':
        $hash = safetxt($_POST['hash']);
        $id   = intval($_POST['id']);
        if (\LaneWeChat\Core\OpenExt::RemoveKewWord($id, WECHAT_APPID)===true) {
            \LaneWeChat\Response('删除成功', 'ok');
        }
        \LaneWeChat\Response('删除失败');
        break;
    case 'Image':
        $username = $_GET['u'];
        $url = "https://mp.weixin.qq.com/cgi-bin/verifycode?username={$username}&r=".time();
        //必须绝对路径
        $file = dirname(__FILE__).'/cookie/cookie_'.$username.'.txt';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0 );
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2 );
        curl_setopt($curl, CURLOPT_TIMEOUT, 10 );
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_COOKIEJAR, $file);
        $res = curl_exec ($curl);
        curl_close ( $curl );
        header("Content-type:image/jpeg");
        echo $res;
        break;
    case 'RemoveAccount':
        $id = intval($_POST['account']);
        if (\LaneWeChat\Core\Ext::RemoveAccount($id)===true) {
            echo 1;
        }
        break;
    case 'TestInsert':
        $sql = <<<SQL
insert into pft_wx_resp(rid,keyword,response,create_time) values
(118,'EVENT_SUBSCRIBE','IMAGE|tttt|http://photos.tuchong.com/384359/m/28508631.jpg|在稍低版本的现代浏览器中|http://t.cn/RZBPZPg',now()),
(118,'EVENT_SUBSCRIBE','IMAGE|abc|http://photos.tuchong.com/384359/m/28508630.jpg|晚霞映照石柱|http://t.cn/RZBPZPg',now()),
(118,'EVENT_SUBSCRIBE','IMAGE|def|http://photos.tuchong.com/384359/m/28508623.jpg|梦幻家园|http://t.cn/RZBPZPg',now())
SQL;

        $ret = \LaneWeChat\Core\Db::Connect()->exec($sql);
        var_dump($ret);
        break;
    case 'verifycode'://设置uu_wx_member_pft表的接收通知帐号
        $id = $_POST['id']+0;
        $code = intval($_POST['code']);
        if(!$id) exit('{"code":101,"msg":"操作失败"}');
        if ($code!=0 && $code!=1 ) exit('{"code":101,"msg":"参数错误"}');
        $sql = "update uu_wx_member_pft set verifycode={$code} where id=$id limit 1";
        if($GLOBALS['le']->query($sql))  exit('{"code":200,"msg":"设置成功"}');
        else  exit('{"code":101,"msg":"操作失败"}');
        break;
    default:
        break;
}
